package com.hxzy.aspect;


import com.hxzy.common.annon.RateLimiter;
import com.hxzy.common.enums.LimitType;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.exception.ShopException;
import com.hxzy.common.util.IpUtil;
import com.hxzy.common.util.ServletUtils;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

/**
 * 限流处理
 *
 * @author
 */
@Log4j2
@Aspect
@Component
public class RateLimiterAspect{


    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * lua脚本  在shop-common-redis项目中RedisConfig.java中配置的
     */
    private RedisScript<Long> limitScript;

    @Autowired
    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setLimitScript(RedisScript<Long> limitScript)  {
        this.limitScript = limitScript;
    }

    /**
     * 前缀增强
     * @param point
     * @param rateLimiter
     * @throws Throwable
     */
    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable
    {
        //redis前缀
        String key = rateLimiter.key();
        //redis过期时间
        int time = rateLimiter.time();
        //请求次数
        int count = rateLimiter.count();

        String combineKey = getCombineKey(rateLimiter, point);

        //redisKey字符串 转换为 List类型
        List<Object> keys = Collections.singletonList(combineKey);

        try
        {
            //T                       execute(RedisScript<T> script, List<K> keys, Object... args)
            Long number = redisTemplate.execute(limitScript, keys, count, time);

            if ((number==null) || number.intValue() > count) {
                throw new ShopException( rateLimiter.message());
            }

            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new ShopException(rateLimiter.message());
        }
    }

    /**
     * 生成redis的规则
     *  1)、rate_limit:ip_类.方法
     *  2)、rate_limit:类.方法
     * @param rateLimiter
     * @param point
     * @return
     */
    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point)
    {
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());
        if (rateLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtil.getIpAddr(ServletUtils.getRequest())).append("-");
        }
//        MethodSignature signature = (MethodSignature) point.getSignature();
//        Method method = signature.getMethod();
//        Class<?> targetClass = method.getDeclaringClass();
//        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());

        String methodName=point.getSignature().toString();
        String[] strArr = methodName.split(" ");

        //设定方法名
        stringBuffer.append(strArr[1]);

        return stringBuffer.toString();
    }
}
